from rest_framework import viewsets
from rest_framework.views import APIView
from .serializers import *


from .filter import *


from django.db.models import F

from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.filters import OrderingFilter
from utils.CustomPageNumberPagination import CustomPageNumberPagination
from utils.request_utils import get_response_by_errcode
from rest_framework.response import Response
from rest_framework import status
from  django.http import JsonResponse

from celery_tasks.send_email.tasks import send_verify_email
from celery_tasks.send_sms.tasks import task_send_sms

import logging
logger = logging.getLogger('django')
from .SaltAPI import SaltApi


class SaltMasterViewSet(viewsets.ModelViewSet):
    '''
    SaltMaster 视图级
    '''
    queryset = SaltMaster.objects.all().order_by(F('id').asc())  # 强制按照 id 升序排序
    serializer_class = SaltMasterSeralizer
    filter_backends = [DjangoFilterBackend, OrderingFilter]
    filterset_class = SaltMasterFilter
    ordering_fields = ['id']
    pagination_class = CustomPageNumberPagination


    def get_serializer_context(self):
        '''
        重写serializer_context 传入request
        :return: context
        '''
        context = super(SaltMasterViewSet, self).get_serializer_context()
        context['request'] = self.request
        return context


class HostViewSet(viewsets.ModelViewSet):
    '''
    主机 视图级
    '''
    queryset = Host.objects.all().order_by(F('id').asc())  # 强制按照 id 升序排序
    serializer_class = HostSeralizer
    filter_backends = [DjangoFilterBackend, OrderingFilter]
    filterset_class = HostFilter
    ordering_fields = ['id']
    pagination_class = CustomPageNumberPagination


    def get_serializer_context(self):
        '''
        重写serializer_context 传入request
        :return: context
        '''
        context = super(HostViewSet, self).get_serializer_context()
        context['request'] = self.request
        return context


class SaltAuthViewSet(viewsets.ModelViewSet):
    '''
    主机认证 视图级
    '''
    queryset = SaltAuth.objects.all().order_by(F('id').asc())  # 强制按照 id 升序排序
    serializer_class = SaltAuthSeralizer
    filter_backends = [DjangoFilterBackend, OrderingFilter]
    filterset_class = SaltFilter
    ordering_fields = ['id']
    pagination_class = CustomPageNumberPagination

    def get_serializer_context(self):
        '''
        重写serializer_context 传入request
        :return: context
        '''
        context = super(SaltAuthViewSet, self).get_serializer_context()
        context['request'] = self.request
        return context







class SaltMinionsView(APIView):
    def get(self, request, s_type):
        '''
        获取salt minions
        :param request: HTTP 请求对象
        :param s_type: salt minions 类型
        :return: JSON 响应
        '''
        try:
            saltapi = SaltApi()
            data = saltapi._handle_add_salt_auth(s_type=s_type)
            return  get_response_by_errcode(data)
        except Exception as e:
            logger.error("获取salt minions异常：%s"%e)
            data = {"errcode": 404, "mess": "获取salt minions【%s】" % e}
            return  get_response_by_errcode(data)



class AuthSaltMinions(APIView):
    '''
    认证salt-minion
    '''

    def post(self,request,s_type,pk):


        try:
            saltauth = SaltAuth.objects.get(id=pk)
        except SaltAuth.DoesNotExist:
            data = {"errcode": 404, "mess": "没有找到需要认证的主机id【%s】" % pk}
            return get_response_by_errcode(data)
        else:
            salt_client = saltauth.saltname

            saltapi = SaltApi()
            data = saltapi._handle_salt_client_auth(salt_client, s_type)



            return get_response_by_errcode(data)










#测试异步任务
def test_send_email(request):
    print('调用异步任务')
    task_send_sms.delay('18806207447','测试一下异步短信')
    from django.http import HttpResponse
    return HttpResponse("Email sent")

